package com.dinstar.dinlink.core;

import android.content.Context;
import android.content.SharedPreferences;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;

import androidx.security.crypto.EncryptedSharedPreferences;
import androidx.security.crypto.MasterKeys;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Objects;

import javax.crypto.KeyGenerator;

public class VFS {
    private final static String TAG = "[VFS]";

    private final static String TRANSFORMATION = "AES/GCM/NoPadding";
    private final static String ANDROID_KEY_STORE = "AndroidKeyStore";
    private final static String ALIAS = "vfs";
    private final static int LINPHONE_VFS_ENCRYPTION_AES256GCM128_SHA256 = 2;
    private final static String VFS_IV = "vfsiv";
    private final static String VFS_KEY = "vfskey";
    private final static String ENCRYPTED_SHARED_PREFS_FILE = "encrypted.pref";

    public static Boolean isEnabled(Context context) {
        SharedPreferences preferences = getEncryptedSharedPreferences(context);
        if (preferences == null) {
            return false;
        }
        return preferences.getBoolean("vfs_enabled", false);
    }

    public static void setup(Context context) {
        SharedPreferences preferences = getEncryptedSharedPreferences(context);
        if (preferences == null) {
            return;
        }
        if (preferences.getString(VFS_IV, null) == null) {

        }
    }

    private static void generateSecretKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEY_STORE);
        keyGenerator.init(new KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
                        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                        .build()
        );
        keyGenerator.generateKey();
    }

    private static SharedPreferences getEncryptedSharedPreferences(Context context) {
//        MasterKey masterKey = MasterKeys.
        try {
            return EncryptedSharedPreferences.create(
                    ENCRYPTED_SHARED_PREFS_FILE,
                    MasterKeys.AES256_GCM_SPEC.getKeystoreAlias(),
                    context,
                    EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
                    EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM);
        } catch (GeneralSecurityException | IOException e) {
            return null;
        }
    }
}
